﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Messaging;

namespace GroupChat2013.Common
{
    /// <summary>
    /// 委托
    /// </summary>
    public delegate void Action();

    /// <summary>
    ///  带返回值的委托
    /// </summary>
    /// <typeparam name="TResult">返回值类型</typeparam>
    /// <returns></returns>
    public delegate TResult Func<TResult>();

    /// <summary>
    /// 异步委托调用工具类,利用多线程处理防止界面卡顿
    /// </summary>
    public class AsyncClient
    {
        /// <summary>
        /// 异步委托调用
        /// </summary>
        /// <param name="method">需要调用的方法委托</param>
        /// <param name="callBack">方法执行完成回调委托</param>
        /// <returns></returns>
        public static IAsyncResult AsyncCall(Action method, Action callBack)
        {
            return method.BeginInvoke((a) =>
             {
                 AsyncResult ar = (AsyncResult)a;
                 Action f = a.AsyncState as Action;
                 f.EndInvoke(a);
                 if (callBack != null)
                     callBack();
             }, null);
        }

        /// <summary>
        /// 泛型异步委托调用
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="method">需要调用的方法委托</param>
        /// <param name="callBack">方法执行完成回调委托</param>
        /// <returns></returns>
        public static IAsyncResult AsyncCall<T>(Func<T> method, Action<T> callBack)
        {
            return method.BeginInvoke((a) =>
              {
                  AsyncResult ar = (AsyncResult)a;
                  Func<T> f = ar.AsyncDelegate as Func<T>;
                  T t = f.EndInvoke(a);
                  if (callBack != null)
                      callBack(t);
              }, null);
        }
    }
}
